#include "image.h"
#include "utils.h"
#include "blas.h"
#include "cuda.h"
#include <stdio.h>
#include <math.h>
#include <assert.h>

int windows = 0;

float colors[6][3] = {{1, 0, 1}, {0, 0, 1}, {0, 1, 1}, {0, 1, 0}, {1, 1, 0}, {1, 0, 0}};

static void set_pixel(image m, int x, int y, int c, float val) {
    if (x < 0 || y < 0 || c < 0 || x >= m.w || y >= m.h || c >= m.c) return;
    assert(x < m.w && y < m.h && c < m.c);
    m.data[c * m.h * m.w + y*m.w + x] = val;
}

static float get_pixel(image m, int x, int y, int c) {
    assert(x < m.w && y < m.h && c < m.c);
    return m.data[c * m.h * m.w + y * m.w + x];
}

static void add_pixel(image m, int x, int y, int c, float val) {
    assert(x < m.w && y < m.h && c < m.c);
    m.data[c * m.h * m.w + y *m.w + x] += val;
}

static image make_empty_image(int w, int h, int c) {
    image out;
    out.data = 0;
    out.h = h;
    out.w = w;
    out.c = c;
    return out;
}

image make_image(int w, int h, int c) {
    image out = make_empty_image(w, h, c);
    out.data = calloc(h * w * c, sizeof(float));
    return out;
}

image resize_image(image im, int w, int h) {
    image resized = make_image(w, h, im.c);
    image part = make_image(w, im.h, im.c);

    int r, c, k;
    float w_scale = (float)(im.w - 1) / (w - 1);
    float h_scale = (float)(im.h - 1) / (h - 1);

    for (k = 0; k < im.c; k++) {
        for (r = 0; r < im.h; r++) {
            for (c = 0; c < w; c++) {
                float val = 0;
                if (c == w-1 || im.w == 1) {
                    val = get_pixel(im, im.w - 1, r, k);
                } else {
                    float sx = c * w_scale;
                    int ix = (int) sx;
                    float dx = sx - ix;
                    val = (1 - dx) * get_pixel(im, ix, r, k) + dx * get_pixel(im, ix + 1, r, k);
                }
                set_pixel(part, c, r, k, val);
            }
        }
    }

    for (k = 0; k < im.c; k++) {
        for (r = 0; r < h; r++) {
            float sy = r * h_scale;
            int iy = (int) sy;
            float dy = sy - iy;
            for (c = 0; c < w; c++) {
                float val = (1 - dy) * get_pixel(part, c, iy, k);
                set_pixel(resized, c, r, k, val);
            }
            if (c == h - 1 || im.h == 1) continue;
            for (c = 0; c < w; c++) {
                float val = dy * get_pixel(part, c, iy + 1, k);
                add_pixel(resized, c, r, k, val);
            }
        }
    }

    free_image(part);
    return resized;
}

void free_image(image m) {
    if (m.data) {
        free(m.data);
    }
}